package com.yixin.my.shop.web.be.web.controller;

import com.yixin.my.shop.commons.constant.AppConstant;
import com.yixin.my.shop.domain.TbUser;
import com.yixin.my.shop.web.be.service.TbUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

@Controller
public class LoginController {
    @Autowired
    private TbUserService userService;

    @RequestMapping(value = {"", "login"}, method = RequestMethod.GET)
    public String login() {
        return "login";
    }

    @RequestMapping(value = "login", method = RequestMethod.POST)
    public String login(@RequestParam(required = true) String username,
                        @RequestParam(required = true) String password,
                        Model model,
                        HttpServletRequest request) {

        TbUser tbUser = userService.login(username,password);

        //登入失败
        if (tbUser == null){
            model.addAttribute("message","用户名或者密码输入错误！");
            return login();
        }
        //登入成功
        else {
            //吧TbUser放入session
            request.getSession().setAttribute(AppConstant.SESSION_USER,tbUser);
            return "redirect:main";
        }
    }

}
